//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/21.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import SVProgressHUD
//AppKey
let AppKey = "831557976"
//AppSecret
let AppSecret = "e3f9206c4710492725f21ea2942b6e56"
//授权回调页
let Redirect_Uri = "http://www.apple.com.cn"
class HMOAuthViewController: UIViewController {

    //懒加载控件
    let webView:UIWebView = UIWebView()
    //重写此方法自定义控制器视图
    override func loadView() {
        //解决webView底部的黑色视图，改为透明
        //webView.isOpaque = false
        //设置代理
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        setUpUI()
        requestLogin()
        
        
    }

    func setUpUI() {
        title = "微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消",target:self,action:#selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title:"自动填充",target:self,action:#selector(autofillAction))
    }
    
    //取消登录的方法
    func cancelAction() {
        //dismiss控制器的同时移除等待指示器
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充的方法
    func autofillAction() {
        print("自动填充")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '994768419@qq.com';document.getElementById('passwd').value = 'huangyihan159357'")
    }
    
    //请求第三方登录的方法
    func requestLogin() {
        //URL
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        print("\(url)")
        
        //发送请求
        let request = URLRequest(url:URL(string:url)!)
        webView.loadRequest(request)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
}

//webView代理方法
extension HMOAuthViewController:UIWebViewDelegate {
    //开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断URL是否为空
        guard let url = request.url else {
            //如果url为空，就不加载请求
            print("url为空")
            return false
        }
        
        //执行到此说明nil不为空
        //判断url的绝对路径是否以“Redirect_Uri”开头，若不是就放行
        if !url.absoluteString.hasPrefix(Redirect_Uri) {
            return true
        }
        
        //若绝对路径以以“Redirect_Uri”开头，就取出url的参数,再取出参数中的code
        if let query = url.query,query.hasPrefix("code=") {
            //根据光标位置截取子串,从code=截取到最后
            let code = query.substring(from: "code=".endIndex)
            
            //通过code取到accessToken
            //requestAccesstoken(code: code)
            
            HMUserAccountViewModel.sharedHMUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in
                if isSuccess {
                    print("登录成功")
                    //登录成功后dissmiss掉当前控制器再进入欢迎界面
                    self.dismiss(animated: false, completion: {
                        //发送通知
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: nil)
                    })
                }
            })
        }else{
            //如果参数不是以code=打头就dismiss掉控制器,同时移除等待指示器
            SVProgressHUD.dismiss()
            dismiss(animated: true, completion: nil)
        }

        return false
    }
    

}
